package com.tanhua.app.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.api.PeachblossomApi;
import com.tanhua.app.interceptor.UserHolder;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.mongo.Voice;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.tomcat.util.http.parser.Authorization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Author 沈大哥
 * @Date 2022/3/7 17:16
 * @Version 1.0
 **/
@Service
public class PeachblossomService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private PeachblossomApi peachblossomApi;

    private final String SEND_TIMES= "SEND_TIMES_";
    //发送语音
    public void sendVoice(MultipartFile soundFile) throws IOException {
        //只能发十次语音  将次数存到Redis ,发一次修改一次减一,当次数为零时抛出异常
        String redisName = SEND_TIMES+UserHolder.getUserId();
        //先根据redisName获取Redis中的是否存值
        String times = redisTemplate.opsForValue().get(redisName);
        //存值,不是第一次传音
        if (times != null) {
            if("0".equals(times)){
                throw new RuntimeException("发送语音次数已达上限");
            }
            send(soundFile, redisName);
            //将存的次数-1
            int i = Integer.parseInt(times);
            //删除之前存的,修改之后再存入
            redisTemplate.delete(redisName);
            redisTemplate.opsForValue().set(redisName,(i-1)+"",1, TimeUnit.DAYS);
        }else {
            //第一次传音
            send(soundFile,redisName);
            //初始传音的次数9
            redisTemplate.opsForValue().set(redisName,"9",1, TimeUnit.DAYS);
        }



    }
    //接收语音
    public void receiveVoice(){

    }
    //传音方法抽取
    private void send(MultipartFile soundFile, String redisName) throws IOException {
        //将语音文件上传到FastDFS中
        String oriName = soundFile.getOriginalFilename();
        //获取文件后缀名
        String extName = oriName.substring(oriName.lastIndexOf(".") + 1);
        StorePath storePath = client.uploadFile(soundFile.getInputStream(), soundFile.getSize(), extName, null);
        //获取voiceUrl访问路径
        String voiceUrl = webServer.getWebServerUrl() + storePath.getFullPath();

        //构建语音数据
        Voice voice = new Voice();
        voice.setCreated(System.currentTimeMillis());
        voice.setUserId(UserHolder.getUserId());
        voice.setVideoUrl(voiceUrl);
        voice.setStatus(0);


        peachblossomApi.save(voice);
    }
}
